package com.yj.springbootstudy.mulThread.imooc.juctools;

import java.util.concurrent.Semaphore;

public class SemaphoreTest {

    // 先定义一个Semaphore 信号量对象
    private static Semaphore semaphore = new Semaphore(3);

    public static void main(String[] args) {
        for (int i = 0; i < 10 ; i++) {
            Person person = new Person(semaphore, i);
            new Thread(person).start();
        }
    }
}

class Person implements Runnable{
    private Semaphore semaphore;
    private String personName;

    public Person(Semaphore semaphore, int i) {
        this.semaphore = semaphore;
        this.personName = i+"";
    }

    @Override
    public void run() {
        try {
            semaphore.acquire();
            System.out.println(personName + "获取到了闸机！");
            Thread.sleep(2000);
            System.out.println(personName + "进站");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            semaphore.release();
            System.out.println(personName+ "出了闸机！");
        }
    }
}